package com.frxuexi.user.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.room.AskLeave
import com.frxuexi.user.repository.AskRepository
import java.lang.Exception

class MyDataSource(askRepository: AskRepository,uid:Int):PagingSource<Int,AskLeave>() {
    val askRepository=askRepository
    val uid=uid
    override fun getRefreshKey(state: PagingState<Int, AskLeave>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AskLeave> {
        return try {
            //当前页码
            val currentPage=params.key?:1

            val list = askRepository.askListByPage(uid, currentPage, 10)

            val count = askRepository.getCount(uid)
            val nextPage=if(currentPage<count){
                currentPage+1
            }else{
                null
            }

            LoadResult.Page(
                data = list!!,
                prevKey = null,
                nextKey = nextPage
            )
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }
}